//
//  WalletViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/11/30.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "WalletViewController.h"
#import "WalletLogTableViewCell.h"
#import "UIColor+Hex.h"
#import "UserDefaultUtil.h"
#import "MBProgressHUD+MJ.h"
#import "UserDefaultUtil.h"
#import "HttpReauestParam.h"
#import "AFHTTPRequestOperationManager.h"
#import "DateUtils.h"
#import "HistoryViewController.h"
#import "BankCardViewController.h"
#import "WalletCashViewController.h"
#import "BankCardTableViewCell2.h"
#import "AddBankCardViewController.h"
#import "CashRuleViewController.h"
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试
@interface WalletViewController ()
@property NSArray *data;
@property float amount;

@property (nonatomic, strong) NSTimer *balanceLabelAnimationTimer;
@end

@implementation WalletViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _data = [[NSArray alloc]init];
    // Do any additional setup after loading the view.
    _bg_image.image = [UIImage imageNamed:@"wallet_bg"];
    
    _shuLine1.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    
    [_detailBtn setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];

    _bottomView.backgroundColor = [UIColor whiteColor];
    _line3.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    _line4.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
   // _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, _bottomView.frame.size.height)];
    _tableView.backgroundColor = [UIColor whiteColor];

    _tableView.delegate = self;
    _tableView.dataSource = self;
    UINib *nib = [UINib nibWithNibName:@"BankCardTableViewCell2" bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:@"bank_cell2"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [_bottomView addSubview:_tableView];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 134;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _data.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
 
    
    NSDictionary *dic = _data[indexPath.row];
    
    BankCardTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"bank_cell2"];
    
    cell.bank_image = [cell viewWithTag:11];
    cell.lab_bank = [cell viewWithTag:111];
    cell.lab_num = [cell viewWithTag:1111];
    cell.bg_view = [cell viewWithTag:222];
    
   // UIView *line = [cell viewWithTag:333];
    
    //line.backgroundColor = [UIColor colorWithHexString:@"f2f2f2"];
    [cell.bank_image setImage:[UIImage imageNamed:@"default_image"]];
    [cell.bank_image loadImage:[NSURL URLWithString:dic[@"bankImage"]]];
    
    cell.lab_bank.text = dic[@"bankName"];
    cell.lab_num.text = [NSString stringWithFormat:@"%@",dic[@"bankCard"]];
    cell.bg_view.backgroundColor = [UIColor colorWithHexString:dic[@"bankColor"]];
    
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}


-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath

{
    
    //如果是删除
    
    if(editingStyle==UITableViewCellEditingStyleDelete)
        
    {
        
        [self removeData:[NSString stringWithFormat:@"%i",_data[indexPath.row][@"id"]]];
        
    }
    
}
-(NSString*)tableView:(UITableView*)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath*)indexPath

{
    
    return@"删除";
    
}

//是否允许编辑行，默认是YES

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    return YES;
    
}

-(void) removeData:(NSString *) bankid{
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"id":bankid,@"flag":@"1",@"cardNum":@"",@"carUserName":@"",@"phone":@""};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"bank_card_operator" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    [MBProgressHUD showMessage:@"删除"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        [MBProgressHUD hideHUD];
        if ([data[@"success"] boolValue]) {
            
            
            [self getNumData:nil endDate:nil];
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)back_click:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [self getAmountData];
    int *year = [DateUtils getYear];
    int *month = [[DateUtils getMonth] integerValue];
    
    [self getNumData:[DateUtils getFirstDay:year month:month] endDate:[DateUtils getEndDay:year month:month]];
}
-(void)getAmountData{
    
    NSString *userId = [UserDefaultUtil getUserId];
    NSDictionary *dic =@{@"identifier":userId};
    
    HttpReauestParam *param = [[HttpReauestParam alloc]initWithData:@"wallet_statistics" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        if ([data[@"success"] boolValue]) {
            
            NSDictionary *dic = data[@"result"];
            
           // _lab1.text = [NSString stringWithFormat:@"%@",dic[@"earningsMonth"]];
           // _lab2.text = [NSString stringWithFormat:@"%@",dic[@"walletBalance"]];
            _lab1.text = [NSString stringWithFormat:@"%.2f",[dic[@"earningsAmount"] floatValue]];
            
            [self setNumberTextOfLabel:_lab2 WithAnimationForValueContent:[dic[@"walletBalance"] floatValue]];
            _amount = [dic[@"walletBalance"] floatValue];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
    
}
-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

-(void) getNumData:(NSString *) startDate endDate:(NSString *)endDate{
    
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId };
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"person_binding_bank_card_info_get" content:[self dictionaryToJson:dic] urlType:0];

    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        
        if ([data[@"success"] boolValue]) {
            
            _data = data[@"result"];
            [_tableView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}

- (IBAction)history_click:(id)sender {
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    HistoryViewController *history = [sb instantiateViewControllerWithIdentifier:@"history_view"];
    [self.navigationController pushViewController:history animated:YES];
}

- (IBAction)card_click:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    BankCardViewController *bankVc = [sb instantiateViewControllerWithIdentifier:@"bank_view"];
    bankVc.isCash = NO;
    [self.navigationController pushViewController:bankVc animated:YES];
}
- (IBAction)cash_click:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    WalletCashViewController *vc = [sb instantiateViewControllerWithIdentifier:@"cash_wallet_view"];
    vc.amount = _amount;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)add_content:(id)sender {
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    AddBankCardViewController *addBank = [sb instantiateViewControllerWithIdentifier:@"add_bank_view"];
    [self.navigationController pushViewController:addBank animated:YES];
}

#pragma mark --- 余额显示的动画----
- (void)setNumberTextOfLabel:(UILabel *)label WithAnimationForValueContent:(CGFloat)value
{
    CGFloat lastValue = [label.text floatValue];
    CGFloat delta = value - lastValue;
    if (delta == 0) {
        return;
    }
    
    if (delta > 0) {
        
        CGFloat ratio = value / 30.0;
        
        NSDictionary *userInfo = @{@"label" : label,
                                   @"value" : @(value),
                                   @"ratio" : @(ratio)
                                   };
        _balanceLabelAnimationTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(setupLabel:) userInfo:userInfo repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_balanceLabelAnimationTimer forMode:NSRunLoopCommonModes];
    }
}

- (void)setupLabel:(NSTimer *)timer
{
    NSDictionary *userInfo = timer.userInfo;
    UILabel *label = userInfo[@"label"];
    CGFloat value = [userInfo[@"value"] floatValue];
    CGFloat ratio = [userInfo[@"ratio"] floatValue];
    
    static int flag = 1;
    CGFloat lastValue = [label.text floatValue];
    CGFloat randomDelta = (arc4random_uniform(2) + 1) * ratio;
    CGFloat resValue = lastValue + randomDelta;
    
    if ((resValue >= value) || (flag == 50)) {
        label.text = [NSString stringWithFormat:@"%.2f", value];
        flag = 1;
        [timer invalidate];
        timer = nil;
        return;
    } else {
        label.text = [NSString stringWithFormat:@"%.2f", resValue];
    }
    flag++;
}
- (IBAction)cash_rule_click:(id)sender {
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    CashRuleViewController *rule = [sb instantiateViewControllerWithIdentifier:@"cash_rule_view"];
    [self.navigationController pushViewController:rule animated:YES];
    
}
@end
